import React from 'react';
import { Button, Modal, Avatar, message } from 'antd';
import LoginModal from './LoginModal';

import './index.scss';

class MenuContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loginModal: {
        visible: false,
      },
      isLogin: false
    }
    let user = window.localStorage.getItem('user');
    if (user) {
      window.user = JSON.parse(user);
      this.state.isLogin = true;
    }
  }

  onoffLoginModal = (onoff) => {
    let loginModal = this.state.loginModal;
    loginModal.visible = onoff;
    this.setState({ loginModal: { ...loginModal } });
  }

  handleLogoutBtn = () => {
    Modal.confirm({
      content: '确定退出当前账号吗？',
      okText: '退出',
      cancelText: '取消',
      centered: true,
      onOk: () => {
        window.axios.get('/logout')
        .then((response) => {
          message.success('退出成功！');
          window.localStorage.removeItem('user');
          this.setState({ isLogin: false });
        })
        .catch((error) => {
          console.log(error);
        });
      }
    });
  }

  render() {

    return (
      <div className="menu-content">
        <div>
          {
            this.state.isLogin ?
            (
              <div className="login-box">
                <div className="avatar">
                  <Avatar size={80} src={window.user.profile.avatarUrl} />
                </div>
                <p className="login-info">{window.user.profile.nickname}</p>
              </div>
            ) : 
            (
              <div className="login-box">
                <p className="login-info">使用网易云音乐账号登录</p>
                <p>
                  <Button onClick={ () => { this.onoffLoginModal(true) } }>立即登录</Button>
                </p>
              </div>
            )
          }
          <p>每日推荐</p>
          <p>我创建的歌单</p>
        </div>

        {
          this.state.isLogin ?
          (
            <div className="logout-btn" onClick={this.handleLogoutBtn}>
              <span>退出登录</span>
            </div>
          ) : ''
        }

        <Modal
          wrapClassName="abc"
          closable={ false }
          visible={ this.state.loginModal.visible }
          title="登录"
          footer={ null }
          width="400px"
          maskClosable={ false }
          onCancel={() => { this.onoffLoginModal(false) }}
        >
          <LoginModal onClose={() => { this.onoffLoginModal(false) }} loginSuccess={() => { this.setState({ isLogin: true }) }} />
        </Modal>
      </div>
    )
  }
}

export default MenuContent;
